// 定义医院科室相关接口
const express = require('express');
const router = express.Router();
const Response = require('../utils/Response.js');

// 引入mysql连接池
const pool = require('../utils/db.js');
const { error } = require('../utils/Response.js');

// 查询所有医院科室
router.get("/department-all", async (req, resp) => {
  // 获取请求参数   get请求的参数封装在req.query中
  let { page, pagesize } = req.query;
  // 执行查询数组业务
  try {
    let startIndex = (page - 1) * pagesize;
    let size = parseInt(pagesize);
    let sql = "select * from hospital_Department limit ?,?";
    let result = await pool.querySync(sql, [startIndex, size]);
    // 执行查询总条目数
    let sql2 = "select count(*) as count from hospital_Department";
    let result2 = await pool.querySync(sql2, [startIndex, size]);
    let total = result2[0].count;
    resp.send(
      Response.ok({ page: parseInt(page), pagesize: size, total, result })
    );
  } catch (error) {
    resp.send(Response.error(error));
  }
});

// 查询该医院下的所有科室
router.post('/hospital_department',(req,res) =>{
  let {hospital_id} = req.body
  let sql = 'select * from hospital_Department where hospital_id=?'
  pool.query(sql,[hospital_id],(err,result) =>{
    if(err){
      res.send(Response.error(500,error))
      throw err
    }
    // 将结果返回给客户端
    res.send(Response.ok(result))
  })
})

// 为该医院新增科室
router.post('/hospital_department/add',(req,res) =>{
  let {hospital_id,d_id,d_name} = req.body
  let sql = 'insert into hospital_Department (hospital_id,d_id,d_name) values (?,?,?)'
  pool.query(sql,[hospital_id,d_id,d_name],(err,result) =>{
    if(err){
      res.send(Response.error(500,error))
      throw err
    }
    // 将结果返回给客户端
    res.send(Response.ok(result))
  })
})

// 删除该医院科室
router.delete('/hosital_department/delete',(req,res) =>{
  let {d_id} = req.body
  let sql = 'delete from hospital_Department where d_id=?'
  pool.query(sql,[d_id],(err,result) =>{
    if(err){
      res.send(Response.error(500,error))
      throw error
    }
    // 将结果返回给客户端
    res.send(Response.ok(result))
  })
})

// 修改科室
router.post('/hosital_department/update',(req,res) =>{
  let {d_name,d_id} = req.body
  let sql = 'update hospital_Department set d_name=? where d_id=?'
  pool.query(sql,[d_name,d_id],(err,result) =>{
    if(err){
      res.send(Response.error(500,error))
      throw err
    }
    // 将结果返回给客户端
    res.send(Response.ok(result))
  })
})

module.exports = router